import {
  getCardList
} from "../../apis/card";
import {
  notice
} from '../../apis/group';
import {
  upload,
  globalData
} from '../../utils/request';
import cnchar from 'cnchar';
const app = getApp();

Page({
  data: {
    headTop: null,
    headHeight: null,
    popupShow: false,
    sortPopupShow: false,
    cardMenuShow: false,
    sort: 'default',
    rankList: [],
    indexList: [],
    searchList: [],
    number: 0,
    clickCard: {}
  },

  onShareAppMessage(e) {
    if (e.from === 'button') {
      return {
        title: `${this.data.clickCard.userName}的快名片`,
        path: `/pages/cardPreview/index?type=share&cardId=${this.data.clickCard.cardId}`,
        imageUrl: `${this.data.clickCard.avatar}`
      }
    } else if (e.from === 'menu') {
      return {
        title: '快闪名片',
        path: '/pages/start/index',
        imageUrl: '/images/fastCard.png'
      }
    };
  },

  onHide() {
    this.setData({
      popupShow: false
    });
  },

  onLoad() {
    let menu = wx.getMenuButtonBoundingClientRect();
    this.setData({
      headTop: menu.top + 2,
      headHeight: menu.height,
      showGroupBtn: globalData.checkIn
    });
  },

  onShow() {
    this.getMailList();
    this.getNotice();
  },

  // 获取通讯录
  getMailList() {
    getCardList({
      status: 1,
      cardType: 2
    }).then(res => {
      if (res.data.code === 200) {
        let {
          rows
        } = res.data;
        let indexList = [];
        rows.forEach(v => {
          if (v.noticeUpate === 1) {
            this.setData({
              showUpdate: true
            });
          };
          indexList.push(v.userName.substr(0, 1).spell('first'));
        });
        indexList = [...new Set(indexList.sort())];
        let rankList = indexList.map(v => {
          return {
            rank: v,
            cardList: []
          }
        });
        rows.forEach(v => {
          rankList.forEach(val => {
            if (v.userName.substr(0, 1).spell('first') === val.rank) {
              if (v.imageList) {
                v.imageList = v.imageList.map(img => {
                  if (!new RegExp('^https://').test(img) && !new RegExp('^http://').test(img)) img = app.globalData.url + img;
                  return img
                });
              };
              if (!new RegExp('^https://').test(v.avatar) && !new RegExp('^http://').test(v.avatar)) v.avatar = app.globalData.url + v.avatar;
              val.cardList.push(v);
            };
          });
        });
        this.setData({
          rankList: rankList,
          indexList: indexList
        });

        setTimeout(() => {
          this.getRankTop();
        }, 500);
      };
    });
  },

  getNotice() {
    notice().then(res => {
      if (res.data.code === 200) {
        let {
          data
        } = res.data;
        for (let key in data) {
          if (data[key] !== 0) wx.showTabBarRedDot({
            index: 2
          });
        };
      };
    });
  },

  getRankTop() {
    let query = wx.createSelectorQuery();
    this.data.indexList.forEach(v => {
      query.select('#jump' + v).boundingClientRect();
    });
    query.exec(v => {
      this.setData({
        indexList: v
      });
    });
  },

  // 页面滚动
  jumpRank(e) {
    let {
      rank
    } = e.currentTarget.dataset;
    let query = wx.createSelectorQuery();
    query.select('.search-box').boundingClientRect(rect => {
      this.data.indexList.forEach(v => {
        if ('jump' + rank === v.id) {
          wx.pageScrollTo({
            duration: 300,
            scrollTop: v.top - rect.height
          });
        };
      });
    }).exec();
  },

  // 弹出显示方式
  showSortPopup() {
    this.setData({
      sortPopupShow: !this.data.sortPopupShow
    });
  },
  // 隐藏显示方式
  hideSortPopup() {
    this.setData({
      sortPopupShow: false
    });
  },
  // 切换显示方式
  handleSwitch(e) {
    let {
      type
    } = e.currentTarget.dataset;
    this.setData({
      sort: type,
      sortPopupShow: false
    });
  },

  // 弹出
  showPopup() {
    this.setData({
      popupShow: true
    });
  },
  // 隐藏
  hidePopup() {
    this.setData({
      popupShow: false,
      sortPopupShow: false,
      cardMenuShow: false
    });
  },
  // 弹出名片菜单
  showCardMenu(e) {
    let {
      card
    } = e.currentTarget.dataset;
    this.setData({
      cardMenuShow: true,
      clickCard: card
    });
  },
  hideCardMenu() {
    this.setData({
      cardMenuShow: false,
      clickCard: {}
    });
  },
  cardMenuAction(e) {
    let {
      index
    } = e.currentTarget.dataset;
    if (index === '0') {
      this.handlePreview(this.data.clickCard.relCardId, this.data.clickCard.cardId);
    } else if (index === '1') {
      this.dialCall(this.data.clickCard.relCardId, this.data.clickCard.userName, this.data.clickCard.avatar, this.data.clickCard.phone);
    } else if (index === '2') {
      this.goToEditOther(this.data.clickCard.cardId);
    } else if (index === '3') {
      this.deleteCard(this.data.clickCard.cardId);
    }
  },

  // 编辑他人名片
  goToEditOther(id) {
    wx.navigateTo({
      url: `/pages/fillInformation/index?type=otherEdit&cardId=${id}`,
    })
  },

  // 拨号
  dialCall(id, name, avatar, phone) {
    wx.makePhoneCall({
      phoneNumber: phone,
      success: res => {
        let time = Date.parse(new Date());
        let obj = {};
        obj.cardId = id;
        obj.name = name;
        obj.phone = phone;
        obj.avatar = avatar;
        obj.time = time;
        try {
          var value = wx.getStorageSync('history');
          if (value) {
            value = JSON.parse(value);
            value.forEach((v, i) => {
              if (v.phone === obj.phone) {
                value.splice(i, 1)
              }
            })
            value.unshift(obj);
            wx.setStorage({
              data: JSON.stringify(value),
              key: 'history',
            })
          } else {
            let arr = [];
            arr.push(obj);
            wx.setStorage({
              data: JSON.stringify(arr),
              key: 'history',
            })
          }
        } catch (e) {}
      }
    });
  },

  // 拍摄名片
  handleShot() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['camera'],
      success: res => {
        this.distinguish(res.tempFilePaths[0]);
      }
    });
  },
  // 识别名片
  distinguish(path) {
    upload(path).then(res => {
      let {
        data,
        code
      } = JSON.parse(res.data);
      if (code === 200) {
        wx.navigateTo({
          url: `/pages/editCard/index?type=distinguish&src=${data}`
        });
      };
    });
  },

  // 手动添加
  handleAdd() {
    wx.navigateTo({
      url: '/pages/editCard/index?type=addOther',
      success: res => {
        this.setData({
          popupShow: false
        });
      }
    });
  },

  // 扫名片码
  handleScanCode() {
    wx.scanCode({
      success: res => {
        if (new RegExp('groupDetails').test(res.path)) {
          let str = res.path.substr(res.path.indexOf('=') + 1);
          let scene = decodeURIComponent(str);
          let arr = scene.split('&');
          let groupId = arr[0].substr(3);
          wx.setStorageSync('selectGroup', JSON.stringify({
            groupId: groupId,
            from: 'qrcode'
          }));
          wx.switchTab({
            url: '/pages/groupDetails/index',
          });
        } else if (new RegExp('cardPreview').test(res.path)) {
          let str = res.path.substr(res.path.indexOf('?') + 1);
          let scene = decodeURIComponent(str);
          let cardId = scene.replace(/[^0-9]/ig, "");
          wx.navigateTo({
            url: `/pages/cardPreview/index?cardId=${cardId}&type=qrCode`
          });
        };
      },
      fail: res => {
        wx.showToast({
          title: '二维码无效',
          icon: 'none'
        });
      }
    });
  },

  // 查看好友名片
  handlePreview(e) {
    let {
      id,
      rid
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/cardDetails/index?cardId=${id}&from=mailList`,
    });
    // if (rid) {
    //   wx.navigateTo({
    //     url: `/pages/cardPreview/index?from=mailList&cardId=${id}`
    //   });
    // } else {
    //   wx.navigateTo({
    //     url: `/pages/personalInfo/index?from=mailList&cardId=${id}`
    //   });
    // };
  },

  handleCancel() {
    this.setData({
      showUpdate: false
    })
  },
  // 输入框搜索
  handleInput(e) {
    let {
      value
    } = e.detail;
    let regExp = new RegExp(`${value}`);
    let arr = [];
    this.data.rankList.forEach(v => {
      v.cardList.forEach(v => {
        if (regExp.test(v.phone) || regExp.test(v.userName) || regExp.test(v.labels) || regExp.test(v.company) || regExp.test(v.post)) {
          arr.push(v);
        };
      })
    });
    if (value === '') {
      this.setData({
        isSearch: false,
        inputValue: value,
        searchList: []
      });
    } else {
      this.setData({
        inputValue: value,
        searchList: arr,
        isSearch: true
      });
    }
  },
  // 删除卡片
  deleteCard(id) {
    wx.showModal({
      title: '删除',
      content: '确定删除此名片吗',
      success: res => {
        if (res.confirm) {
          request({
            url: `/api/auth/card/deleted/other/${id}`,
            header: {
              'content-type': 'application/x-www-form-urlencoded',
              sessionid: app.globalData.sessionid
            }
          }).then(res => {
            if (res.data.code === 0) {
              this.getMailList();
            }
          })
        }
      }
    })
  },
  // 更新名片
  handleUpdate(e) {
    let {
      id
    } = e.currentTarget.dataset;
    wx.showModal({
      title: '更新',
      content: '是否更新此名片？',
      success: res => {
        if (res.confirm) {
          // request({
          //   url: `/api/auth/card/relate/direct/${id}`,
          // }).then(res => {
          //   if (res.data.code === 0) {
          //     this.getMailList();
          //   }
          // })
        }
      }
    })
  },
  // 选择更新
  handleSelectUpdate(e) {
    let {
      phone,
      id
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/updateCard/index?phone=${phone}&cardId=${id}`,
    })
  },

  emptyFunction() {}
})